package com.showsu.editor.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.showsu.editor.dao.TblUserPrivilegeMapper;
import com.showsu.editor.entity.doo.UserPrivilege;
import com.showsu.editor.entity.po.TblUserPrivilege;
import com.showsu.editor.enums.DeleteStatusEnum;
import com.showsu.editor.enums.UserExpPackageTypeEnum;
import com.showsu.editor.enums.UserPrivilegeEnum;
import com.showsu.editor.enums.VipLevelEnum;
import com.showsu.editor.service.IUserExppackageService;
import com.showsu.editor.service.IUserPrivilegeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: William
 * @Description:
 * @Date: Created in 2:33 下午 2024/9/14
 * @Modified By:
 */
@Service
@Slf4j
public class UserPrivilegeServiceImpl extends ServiceImpl<TblUserPrivilegeMapper, TblUserPrivilege> implements IUserPrivilegeService {

    @Autowired
    private TblUserPrivilegeMapper tblUserPrivilegeMapper;

    @Autowired
    private IUserExppackageService userExppackageService;

    @Override
    public UserPrivilege queryByUserIdAndPrivilegeName(Long userId, String privilegeName) {
        if (userId == null || StringUtils.isBlank(privilegeName)) {
            return null;
        }
        TblUserPrivilege tblUserPrivilege = tblUserPrivilegeMapper.selectOne(new QueryWrapper<TblUserPrivilege>().lambda()
                .eq(TblUserPrivilege::getUserId, userId)
                .eq(TblUserPrivilege::getPrivilegeName, privilegeName)
                .eq(TblUserPrivilege::getFlag, DeleteStatusEnum.Normal.getCode())
                .last("limit 1"));
        return tblUserPrivilege == null ? null : BeanUtil.copyProperties(tblUserPrivilege, UserPrivilege.class);
    }

    @Override
    public int exipreUserPrivilege(Long userId) {
        if (userId == null) {
            return 0;
        }
        LambdaUpdateWrapper<TblUserPrivilege> updateWrapper = new UpdateWrapper<TblUserPrivilege>().lambda()
                .eq(TblUserPrivilege::getUserId, userId)
                .eq(TblUserPrivilege::getFlag, DeleteStatusEnum.Normal.getCode());
        TblUserPrivilege user = new TblUserPrivilege();
        user.setRemainTimes(0);
        return tblUserPrivilegeMapper.update(user, updateWrapper);
    }

    @Override
    public int updateUserPrivilege(Long userId, String privilegeName, Integer remainTimes) {
        if (userId == null || StringUtils.isBlank(privilegeName) || remainTimes == null) {
            return 0;
        }
        LambdaUpdateWrapper<TblUserPrivilege> updateWrapper = new UpdateWrapper<TblUserPrivilege>().lambda()
                .eq(TblUserPrivilege::getUserId, userId)
                .eq(TblUserPrivilege::getPrivilegeName, privilegeName)
                .eq(TblUserPrivilege::getFlag, DeleteStatusEnum.Normal.getCode());
        TblUserPrivilege user = new TblUserPrivilege();
        user.setRemainTimes(remainTimes);
        int num = tblUserPrivilegeMapper.update(user, updateWrapper);
        //若库里没有用户对应的权限数据，这种情况通常是开发了新的功能，历史付费用户没有对应权限
        if (num == 0) {
            TblUserPrivilege newRecord = new TblUserPrivilege(userId, privilegeName.toLowerCase(), remainTimes);
            tblUserPrivilegeMapper.insert(newRecord);
        }
        return num;
    }

    @Override
    @Transactional
    public int handleUserPrivilege(Long userId, VipLevelEnum vipLevelEnum, Date vipEndTime, String orderTradeNo) {
        if (userId == null || vipLevelEnum == null) {
            return 0;
        }
        //先把老的权益逻辑删除
        List<TblUserPrivilege> existedUserPrivilege = tblUserPrivilegeMapper.selectList(
                new QueryWrapper<TblUserPrivilege>().lambda()
                .eq(TblUserPrivilege::getUserId, userId)
                .eq(TblUserPrivilege::getFlag, DeleteStatusEnum.Normal.getCode()));
        if (! CollectionUtils.isEmpty(existedUserPrivilege)) {
            List<Long> existedUserPrivilegeIds = existedUserPrivilege.stream().map(item -> item.getId()).collect(Collectors.toList());
            int num = tblUserPrivilegeMapper.deleteBatchIds(existedUserPrivilegeIds);
            log.info("逻辑删除用户{}的老权益{}条，新的套餐id:{}", userId, num, vipLevelEnum.getCode());
        }
        //插入新的权益逻辑删除
        List<TblUserPrivilege> userPrivilegeList = new ArrayList<>();
        userPrivilegeList.add(new TblUserPrivilege(userId, UserPrivilegeEnum.XHSLIVE.getCode(), vipLevelEnum.getXhsLive()));
        userPrivilegeList.add(new TblUserPrivilege(userId, UserPrivilegeEnum.XHSCOMMENTSLIVE.getCode(), vipLevelEnum.getXhsCommentsLive()));
        userPrivilegeList.add(new TblUserPrivilege(userId, UserPrivilegeEnum.PHOTOVIDEO.getCode(), vipLevelEnum.getPhotoVideo()));
        userPrivilegeList.add(new TblUserPrivilege(userId, UserPrivilegeEnum.GIFPHOTO.getCode(), vipLevelEnum.getGifPhoto()));
        userPrivilegeList.add(new TblUserPrivilege(userId, UserPrivilegeEnum.COMMENTPHOTO.getCode(), vipLevelEnum.getCommentPhoto()));
        userPrivilegeList.add(new TblUserPrivilege(userId, UserPrivilegeEnum.AI_CHECKTEXT.getCode(), vipLevelEnum.getAiCheckText()));
        userPrivilegeList.add(new TblUserPrivilege(userId, UserPrivilegeEnum.XHS_AWEME_INCLUDED.getCode(), vipLevelEnum.getXhsAwemeIncluded()));
        this.saveBatch(userPrivilegeList);
        //更新用户资源包数据
        userExppackageService.addUserExppackage(userId, UserExpPackageTypeEnum.XHS_AWEME_RANK_QUERY, vipLevelEnum.getXhsAwemeRank(), vipEndTime, orderTradeNo);
        return userPrivilegeList.size();
    }
}
